package puzzle;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;


public class Solver {

	static ArrayList<Tray> oldPositions;
	static ArrayList<Tray> solutions;

	static boolean visitedTray(Tray currentTray,ArrayList<Tray> trayList){
		for(Tray t : trayList){
			if (equalBlocks(currentTray,t.getBlock()))return true;
			}
		return false;
	}

	static boolean equalBlocks(Tray currentTray,ArrayList<Block> bs2){
		int matches = 0;
		ArrayList<Block> bs1 = currentTray.getBlock();
		for(Block b1 : bs1){
			for(Block b2 : bs2){
				if(b1.equals(b2)){
					matches++;
					break;
				}
			}
		}		
		if(matches == bs1.size())return true;
		else {
			matches=0;
			for(Block b1 : bs1){
				for(Block b2 : bs2){
					if((b1.getPosx() == b2.getPosx() && b1.getPosy() == currentTray.getT_width()-b2.getPosy()-b2.getWidth() &&  b1.getWidth() == b2.getWidth() && b1.getHeight() == b2.getHeight())){
						matches++;
						break;
					}
				}
			}
			return (matches == bs1.size());
		}
	}
	public static boolean solve(int depth,Tray myCurrentTray){

		//System.out.println(depth);
		if(myCurrentTray.win()){
			DrawElement.Draw(myCurrentTray);
			System.out.println("win");
			solutions.add(myCurrentTray);
			System.out.println(depth);
			return true;
		}
		if(visitedTray(myCurrentTray,oldPositions)){
			return false;
		}



		oldPositions.add(myCurrentTray.clone());


		for(Block b : myCurrentTray.getBlock()){

			for(int i=1;i<5;i++){
				Tray nextTray = myCurrentTray.clone();
				if(nextTray.moveDirection(nextTray.getBlock().get(myCurrentTray.getBlock().indexOf(b)), i)){
					if(solve(depth+1,nextTray)){
						solutions.add(nextTray);
						return true;
					}
				}

			}
		}
		return false;
	}

	public static void main(String[] args) {
		try {

			Tray myTray = new Tray();
			oldPositions = new ArrayList<Tray>();
			solutions = new ArrayList<Tray>();
			FileInputStream file1 = new FileInputStream(args[0]);
			FileInputStream file2 = new FileInputStream(args[1]);
			ReadFile read = new ReadFile(file1, file2,myTray);

			DrawElement.init(myTray);
			DrawElement.Draw(myTray);
			System.out.println(solve(0,myTray));
			Collections.reverse(solutions);
			for(Tray t : solutions){
				DrawElement.Draw(t);
			}
		} catch (FileNotFoundException e) {
			System.out.println("file not found");
			e.printStackTrace();
		}
	}
}
